﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

using OmniKits.Windows.Design;
using System.Diagnostics;

namespace OmniKits.Windows.Behaviors
{
    public class DragMoveBehavior
        : Behavior<FrameworkElement>
    {
        FrameworkElement _Element;
        CaptureMouseBehavior _CMB = new CaptureMouseBehavior();

        public bool NullifyUnnecessaryMargins { get; set; }

        protected override void OnAttached()
        {
            _Element = this.AssociatedObject;

            _Element.PreviewMouseDown += MouseDown;
            _Element.MouseMove += MouseMove;

            _CMB.Attach(_Element);
        }

        protected override void OnDetaching()
        {
            _Element.PreviewMouseDown -= MouseDown;
            _Element.MouseMove -= MouseMove;

            _CMB.Detach();

            _Element = null;
        }

        Point _InitPos;
        private void MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                Debug.WriteLine("DragMoveBehavior::MouseDown");

                _InitPos = e.GetPosition(_Element);
            }
        }

        private void MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                Debug.WriteLine("DragMoveBehavior::MouseMove");

                var pos = e.GetPosition(_Element);
                _Element.Move(new Point(pos.X - _InitPos.X, pos.Y - _InitPos.Y));
            }
        }
    }
}
